'use strict';

const Service = require('egg').Service;

class OutfitService extends Service {
  // 获取搭配列表
  async getList(userId, options = {}) {
    const { Op } = this.app.Sequelize;
    const {
      page = 1,
      pageSize = 20,
      style,
      season,
      occasion,
      is_favorite,
      keyword,
      sortBy = 'created_at',
      sortOrder = 'DESC',
      minRating,
      maxWearCount,
      minWearCount
    } = options;

    const where = { user_id: userId };

    // 构建查询条件
    if (style) {
      where.style = style;
    }

    if (season) {
      where.season = season;
    }

    if (occasion) {
      where.occasion = { [Op.like]: `%${occasion}%` };
    }

    if (is_favorite !== undefined) {
      where.is_favorite = is_favorite === true || is_favorite === 'true';
    }

    if (keyword) {
      where[Op.or] = [
        { name: { [Op.like]: `%${keyword}%` } },
        { description: { [Op.like]: `%${keyword}%` } },
        { notes: { [Op.like]: `%${keyword}%` } },
      ];
    }

    // 评分筛选
    if (minRating !== undefined) {
      where.rating = { [Op.gte]: minRating };
    }

    // 穿着次数筛选
    if (minWearCount !== undefined || maxWearCount !== undefined) {
      where.wear_count = {};
      if (minWearCount !== undefined) {
        where.wear_count[Op.gte] = minWearCount;
      }
      if (maxWearCount !== undefined) {
        where.wear_count[Op.lte] = maxWearCount;
      }
    }

    const offset = (page - 1) * pageSize;

    // 使用简单的排序，避免字段歧义
    let orderBy = [['created_at', 'DESC']]; // 默认排序

    // 对于可能有歧义的字段，我们在应用层排序
    if (sortBy === 'created_at') {
      orderBy = [['created_at', sortOrder]];
    } else if (sortBy === 'wear_count') {
      orderBy = [['wear_count', sortOrder], ['created_at', 'DESC']];
    } else {
      // 对于last_worn和rating，我们先按created_at排序，然后在应用层重新排序
      orderBy = [['created_at', 'DESC']];
    }

    // 先获取总数（不包含关联查询）
    const total = await this.ctx.model.Outfit.count({ where });

    // 如果需要应用层排序，获取所有数据；否则使用数据库分页
    const needAppSort = sortBy === 'last_worn' || sortBy === 'rating';

    const outfits = await this.ctx.model.Outfit.findAll({
      where,
      order: orderBy,
      limit: needAppSort ? undefined : pageSize,
      offset: needAppSort ? undefined : offset,
      include: [{
        model: this.ctx.model.Clothing,
        as: 'clothes',
        through: {
          model: this.ctx.model.OutfitItem,
          as: 'outfit_item',
          attributes: ['position', 'layer_order', 'is_main'],
          paranoid: false  // 中间表不使用软删除
        },
        attributes: ['id', 'name', 'main_image', 'color', 'category_id'],
        required: false
      }]
    });

    // 获取今日穿搭信息
    const today = new Date().toISOString().split('T')[0];

    const todayWearRecord = await this.ctx.model.WearRecord.findOne({
      where: {
        user_id: userId,
        wear_date: {
          [Op.like]: today + '%'
        }
      }
    });



    // 处理返回数据，确保clothes数组正确并添加今日穿搭标识
    let outfitsWithClothes = outfits.map(outfit => {
      const outfitData = outfit.toJSON ? outfit.toJSON() : outfit;
      const isWearingToday = todayWearRecord &&
        (todayWearRecord.outfit_id === outfit.id ||
         todayWearRecord.outfit_id === parseInt(outfit.id));

      return {
        ...outfitData,
        clothes: outfitData.clothes || [],
        isWearingToday
      };
    });

    // 应用层排序（避免SQL字段歧义）
    if (sortBy === 'last_worn') {
      outfitsWithClothes.sort((a, b) => {
        const dateA = a.last_worn_date ? new Date(a.last_worn_date) : new Date('1970-01-01');
        const dateB = b.last_worn_date ? new Date(b.last_worn_date) : new Date('1970-01-01');
        return sortOrder === 'DESC' ? dateB - dateA : dateA - dateB;
      });
    } else if (sortBy === 'rating') {
      outfitsWithClothes.sort((a, b) => {
        const ratingA = a.rating || 0;
        const ratingB = b.rating || 0;
        return sortOrder === 'DESC' ? ratingB - ratingA : ratingA - ratingB;
      });
    }

    // 如果进行了应用层排序，需要手动分页
    if (needAppSort) {
      const startIndex = (page - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      outfitsWithClothes = outfitsWithClothes.slice(startIndex, endIndex);
    }

    return {
      list: outfitsWithClothes,
      total,
      page,
      pageSize,
      totalPages: Math.ceil(total / pageSize),
    };
  }

  // 根据ID查找搭配
  async findById(id, userId) {
    return await this.ctx.model.Outfit.findOne({
      where: { id, user_id: userId },
      include: [
        {
          model: this.ctx.model.Clothing,
          as: 'clothes',
          through: {
            attributes: ['position', 'layer_order', 'is_main', 'notes'],
            as: 'outfit_item',
            paranoid: false  // 中间表不使用软删除
          },
          include: [
            {
              model: this.ctx.model.Category,
              as: 'category',
              attributes: ['id', 'name'],
            },
          ],
        },
      ],
    });
  }

  // 创建搭配
  async create(outfitData) {
    const { clothing_ids, ...data } = outfitData;
    
    // 创建搭配
    const outfit = await this.ctx.model.Outfit.create(data);
    
    // 添加衣服到搭配
    if (clothing_ids && clothing_ids.length > 0) {
      await this.addClothes(outfit.id, clothing_ids);
    }
    
    return await this.findById(outfit.id, data.user_id);
  }

  // 根据ID更新搭配
  async updateById(id, updateData) {
    const { clothing_ids, ...data } = updateData;
    
    await this.ctx.model.Outfit.update(data, {
      where: { id },
    });
    
    // 如果有衣服更新，先删除旧关联再添加新关联
    if (clothing_ids !== undefined) {
      await this.ctx.model.OutfitItem.destroy({
        where: { outfit_id: id },
      });
      
      if (clothing_ids.length > 0) {
        await this.addClothes(id, clothing_ids);
      }
    }
    
    return true;
  }

  // 根据ID删除搭配
  async deleteById(id) {
    // 删除相关的衣服关联
    await this.ctx.model.OutfitItem.destroy({
      where: { outfit_id: id },
    });
    
    // 删除相关的穿搭记录
    await this.ctx.model.WearRecord.destroy({
      where: { outfit_id: id },
    });
    
    // 软删除搭配
    return await this.ctx.model.Outfit.destroy({
      where: { id },
    });
  }

  // 添加衣服到搭配
  async addClothing(outfitId, clothingId, options = {}) {
    const { position, layer_order = 1, is_main = false, notes } = options;
    
    // 检查是否已存在
    const existing = await this.ctx.model.OutfitItem.findOne({
      where: {
        outfit_id: outfitId,
        clothing_id: clothingId,
      },
    });
    
    if (existing) {
      throw new Error('衣服已在搭配中');
    }
    
    return await this.ctx.model.OutfitItem.create({
      outfit_id: outfitId,
      clothing_id: clothingId,
      position,
      layer_order,
      is_main,
      notes,
    });
  }

  // 批量添加衣服到搭配
  async addClothes(outfitId, clothingIds) {
    const outfitItems = clothingIds.map((clothingId, index) => ({
      outfit_id: outfitId,
      clothing_id: clothingId,
      layer_order: index + 1,
    }));
    
    return await this.ctx.model.OutfitItem.bulkCreate(outfitItems);
  }

  // 从搭配中移除衣服
  async removeClothing(outfitId, clothingId) {
    return await this.ctx.model.OutfitItem.destroy({
      where: {
        outfit_id: outfitId,
        clothing_id: clothingId,
      },
    });
  }

  // 复制搭配
  async copy(outfitId, userId) {
    const originalOutfit = await this.findById(outfitId, userId);
    if (!originalOutfit) {
      throw new Error('搭配不存在');
    }
    
    // 创建新搭配
    const newOutfitData = {
      user_id: userId,
      name: `${originalOutfit.name} - 副本`,
      description: originalOutfit.description,
      style: originalOutfit.style,
      season: originalOutfit.season,
      occasion: originalOutfit.occasion,
      weather: originalOutfit.weather,
      color_scheme: originalOutfit.color_scheme,
      tags: originalOutfit.tags,
    };
    
    const newOutfit = await this.ctx.model.Outfit.create(newOutfitData);
    
    // 复制衣服关联
    if (originalOutfit.clothes && originalOutfit.clothes.length > 0) {
      const outfitItems = originalOutfit.clothes.map(clothing => ({
        outfit_id: newOutfit.id,
        clothing_id: clothing.id,
        position: clothing.outfit_item.position,
        layer_order: clothing.outfit_item.layer_order,
        notes: clothing.outfit_item.notes,
      }));
      
      await this.ctx.model.OutfitItem.bulkCreate(outfitItems);
    }
    
    return await this.findById(newOutfit.id, userId);
  }

  // 获取搭配推荐
  async getRecommendations(userId, options = {}) {
    const { weather, occasion, style, limit = 10 } = options;
    const { Op } = this.app.Sequelize;
    
    const where = { 
      user_id: userId,
      rating: { [Op.gte]: 3 }, // 评分3分以上
    };
    
    // 基于条件筛选
    if (weather) {
      where.weather = { [Op.like]: `%${weather}%` };
    }
    
    if (occasion) {
      where.occasion = { [Op.like]: `%${occasion}%` };
    }
    
    if (style) {
      where.style = style;
    }
    
    return await this.ctx.model.Outfit.findAll({
      where,
      include: [
        {
          model: this.ctx.model.Clothing,
          as: 'clothes',
          attributes: ['id', 'name', 'main_image'],
          through: {
            attributes: [],
            paranoid: false  // 中间表不使用软删除
          },
        },
      ],
      order: [
        ['rating', 'DESC'],
        ['wear_count', 'ASC'], // 优先推荐穿着次数少的
        ['created_at', 'DESC'],
      ],
      limit,
    });
  }

  // 获取搭配统计信息
  async getStats(userId) {
    const { Op } = this.app.Sequelize;
    
    // 按风格统计
    const styleStats = await this.ctx.model.Outfit.findAll({
      where: { 
        user_id: userId,
        style: { [Op.ne]: null },
      },
      attributes: [
        'style',
        [this.app.Sequelize.fn('COUNT', this.app.Sequelize.col('id')), 'count'],
        [this.app.Sequelize.fn('AVG', this.app.Sequelize.col('rating')), 'avg_rating'],
      ],
      group: ['style'],
    });

    // 按季节统计
    const seasonStats = await this.ctx.model.Outfit.findAll({
      where: { 
        user_id: userId,
        season: { [Op.ne]: null },
      },
      attributes: [
        'season',
        [this.app.Sequelize.fn('COUNT', this.app.Sequelize.col('id')), 'count'],
      ],
      group: ['season'],
    });

    // 最受欢迎的搭配
    const popularOutfits = await this.ctx.model.Outfit.findAll({
      where: { user_id: userId },
      order: [
        ['wear_count', 'DESC'],
        ['rating', 'DESC'],
      ],
      limit: 5,
    });

    return {
      style: styleStats,
      season: seasonStats,
      popular: popularOutfits,
    };
  }
}

module.exports = OutfitService;
